/**网络请求封装 */
import axios from "axios";
import qs from "qs";
// 网络请求端口
const PORT = 80;
const TCP = "http";
const host = "127.0.0.1";
axios.defaults.withCredentials = true;
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  return config;
});

// 添加响应拦截器
// axios.interceptors.response.use(
//   function (response) {
//     console.log("数据响应成功", response);
//     return response;
//   },
//   function (error) {
//     console.log("数据响应失败");
//     return Promise.reject(error);
//   }
// );
/**
 * 普通 post请求
 * @param {*} config {port:端口,agr:协议,host:主机名,path:请求地址}
 */
export const post = (config) => {
  let _path;
  if (typeof config === "object") {
    _path = config.path;
  } else if (typeof config === "string") {
    _path = config;
  } else {
    throw new Error("参数");
  }
  let url = `
    ${config.agr ? config.agr : TCP}://${config.host ? config.host : host}:${
    config.port ? config.port : PORT
  }/${_path}`;
  let URL = url.trim();
  return axios({
    method: "POST",
    data: qs.stringify(config.data || null),
    url: URL,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
  });
};
/**
 * 普通get请求
 * @param {*}  同上 data 数据为field=value
 */
export const get = (config) => {
  let _path;
  if (typeof config === "object") {
    _path = config.path;
  } else if (typeof config === "string") {
    _path = config;
  } else {
    throw new Error("参数");
  }
  let url = `
    ${config.agr ? config.agr : TCP}://${config.host ? config.host : host}:${
    config.port ? config.port : PORT
  }/${_path}`;
  let URL = url.trim() + "/" + config.data;
  return axios.get(URL, data);
};
/**
 * 文件上传
 * @param {*} config
 */
export const fileUpload = (config) => {
  let _path;
  if (typeof config === "object") {
    _path = config.path;
  } else if (typeof config === "string") {
    _path = config;
  } else {
    throw new Error("参数");
  }
  let url = `
    ${config.agr ? config.agr : TCP}://${config.host ? config.host : host}:${
    config.port ? config.port : PORT
  }/${_path}`;
  if (config.file && config.file.length > 0) {
    let data = new FormData();

    return axios({
      method: "POST",
      url: url.trim(),
      data,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded format",
      },
    });
  } else {
    throw new Error();
  }
};
/**
 * 批处理请求
 * @param {*} methods
 */
export const batch = (methods) => {
  if (typeof methods === "object" && methods.length > 0) {
    axios.all(methods);
  } else {
    throw new Error("当前并发请求参数错误");
  }
};
